const app = getApp()
const mockData = require('../../utils/data.js')

Page({
  data: {
    order: null,
    status: 'pending', // pending, paid, traveling, reviewing, completed, cancelled, refunded
    travelerNames: '',
    maskedPhone: '',
    maskedEmail: '',
    statusBarHeight: 0,
    navbarHeight: 0
  },
  
  onLoad(options) {
    console.log('订单详情页面 onLoad, options:', options)
    
    // 获取系统信息，用于适配状态栏高度
    try {
      const systemInfo = wx.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0
      // 导航栏总高度 = 状态栏高度 + 88rpx (导航栏内容高度，约44px)
      const navbarHeight = statusBarHeight + 44
      this.setData({
        statusBarHeight: statusBarHeight,
        navbarHeight: navbarHeight
      })
    } catch (e) {
      console.error('获取系统信息失败:', e)
      this.setData({
        statusBarHeight: 0,
        navbarHeight: 44
      })
    }
    
    const id = parseInt(options.id) || parseInt(options.orderId)
    const orderNo = options.orderNo || options.orderNumber
    const status = options.status || 'pending'
    
    // 如果提供了订单编号但没有ID，通过订单编号查找
    if (!id && orderNo) {
      const app = getApp()
      const orders = app.globalData.orders || []
      
      // 尝试从本地存储加载订单
      let localOrders = []
      try {
        localOrders = wx.getStorageSync('orders') || []
      } catch (e) {
        console.error('从本地存储加载订单失败:', e)
      }
      
      // 合并所有订单
      const allOrders = [...orders, ...localOrders]
      
      // 通过订单编号查找订单
      const order = allOrders.find(o => o.orderNumber === orderNo || o.orderNo === orderNo)
      
      if (order && order.id) {
        // 找到订单，使用订单ID加载
        this.loadOrder(order.id, order.status || status)
        return
      } else {
        // 未找到订单
        wx.showToast({
          title: '未找到该订单',
          icon: 'none'
        })
        setTimeout(() => {
          this.goBack()
        }, 1500)
        return
      }
    }
    
    if (!id) {
      console.error('订单ID不存在')
      wx.showToast({
        title: '订单ID错误',
        icon: 'none'
      })
      setTimeout(() => {
        this.goBack()
      }, 1500)
      return
    }
    
    this.loadOrder(id, status)
  },
  
  loadOrder(id, status) {
    try {
      console.log('加载订单详情, id:', id, 'status:', status)
      const orders = app.globalData.orders || []
      let order = orders.find(o => o.id === id || o.id === parseInt(id))
      
      if (!order) {
        console.log('从全局数据中未找到订单，尝试从本地存储加载')
        // 尝试从本地存储加载
        try {
          const localOrders = wx.getStorageSync('orders') || []
          order = localOrders.find(o => o.id === id || o.id === parseInt(id))
        } catch (e) {
          console.error('从本地存储加载订单失败:', e)
        }
      }
      
      if (!order) {
        console.log('未找到订单，使用模拟数据')
        // 模拟订单数据（用于演示，实际应该从接口获取）
        const mockProducts = mockData.products && mockData.products[0] ? [mockData.products[0]] : [{
          id: 1,
          title: '毕业趣旅行-高星好评-四日解锁京城',
          image: 'https://via.placeholder.com/150',
          price: 734,
          date: '2019-06-19',
          adultCount: 2,
          childCount: 1,
          roomCount: 1
        }]
        
        order = {
          id: id,
          products: mockProducts,
          travelers: [
            { name: '张三', idNumber: '430***********1212' },
            { name: '李四', idNumber: '430***********3258' }
          ],
          booker: {
            name: '张三',
            phone: '13333333333',
            email: '12345@qq.com',
            notes: ''
          },
          totalPrice: 734,
          paymentMethod: '微信支付',
          status: status,
          createTime: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          }),
          orderNumber: 'ORD' + id
        }
      }
      
      // 确保订单数据完整
      order = {
        id: order.id || id,
        orderNumber: order.orderNumber || ('ORD' + (order.id || id)),
        status: order.status || status,
        totalPrice: order.totalPrice || 0,
        products: order.products || [],
        travelers: order.travelers || [],
        booker: order.booker || {
          name: '',
          phone: '',
          email: '',
          notes: ''
        },
        paymentMethod: order.paymentMethod || '微信支付',
        createTime: order.createTime || new Date().toLocaleString('zh-CN')
      }
      
      // 处理数据用于显示
      const travelerNames = order.travelers && order.travelers.length > 0 ? 
        order.travelers.map(t => t.name || '').filter(n => n).join('、') : '暂无'
      const maskedPhone = order.booker && order.booker.phone ? 
        (order.booker.phone.length >= 11 ? 
          `${order.booker.phone.substring(0, 3)}****${order.booker.phone.substring(7)}` : 
          order.booker.phone) : ''
      const maskedEmail = order.booker && order.booker.email ? 
        (order.booker.email.includes('@') ? 
          `${order.booker.email.substring(0, 2)}****${order.booker.email.substring(order.booker.email.indexOf('@'))}` : 
          order.booker.email) : ''
      
      console.log('订单数据加载成功:', order)
      
      this.setData({
        order,
        status: order.status || status,
        travelerNames,
        maskedPhone,
        maskedEmail
      })
    } catch (e) {
      console.error('加载订单详情失败:', e)
      wx.showToast({
        title: '加载订单失败',
        icon: 'none'
      })
      setTimeout(() => {
        this.goBack()
      }, 1500)
    }
  },
  
  goToPayment() {
    wx.showModal({
      title: '提示',
      content: '跳转到支付页面',
      success: (res) => {
        if (res.confirm) {
          // 更新订单状态
          const order = this.data.order
          order.status = 'paid'
          this.setData({ order, status: 'paid' })
          
          // 更新订单列表
          const orders = app.globalData.orders || []
          const index = orders.findIndex(o => o.id === order.id)
          if (index !== -1) {
            orders[index] = order
            app.globalData.orders = orders
            wx.setStorageSync('orders', orders)
          }
        }
      }
    })
  },
  
  cancelOrder() {
    wx.showModal({
      title: '提示',
      content: '确定要取消订单吗？',
      success: (res) => {
        if (res.confirm) {
          const order = this.data.order
          order.status = 'cancelled'
          this.setData({ order, status: 'cancelled' })
          
          const orders = app.globalData.orders || []
          const index = orders.findIndex(o => o.id === order.id)
          if (index !== -1) {
            orders[index] = order
            app.globalData.orders = orders
            wx.setStorageSync('orders', orders)
          }
          
          wx.showToast({
            title: '订单已取消',
            icon: 'success'
          })
        }
      }
    })
  },
  
  applyRefund() {
    wx.navigateTo({
      url: `/pages/refund/refund?orderId=${this.data.order.id}`
    })
  },
  
  goToReview() {
    wx.navigateTo({
      url: `/pages/review/review?orderId=${this.data.order.id}`
    })
  },
  
  repurchase() {
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${this.data.order.products[0].id}`
    })
  },
  
  viewRefundDetail() {
    wx.navigateTo({
      url: `/pages/refund-detail/refund-detail?orderId=${this.data.order.id}`
    })
  },
  
  contactService() {
    wx.showToast({
      title: '在线咨询',
      icon: 'none'
    })
  },
  
  contactPhone() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567'
    })
  },
  
  viewTravelerDetail() {
    wx.showModal({
      title: '出行人详情',
      content: this.data.order.travelers.map(t => `${t.name} ${t.idNumber}`).join('\n'),
      showCancel: false
    })
  },
  
  goBack() {
    const pages = getCurrentPages()
    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.navigateTo({
        url: '/pages/order-list/order-list'
      })
    }
  }
})

